'use client';

import { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import dynamic from 'next/dynamic';

// 动态导入ECharts组件以避免SSR问题
const ReactECharts = dynamic(() => import('echarts-for-react'), { ssr: false });

interface RSIData {
  timestamp: string;
  rsi: number;
  price: number;
}

interface Token {
  id: string;
  symbol: string;
  name: string;
  chain: string;
  contractAddress: string;
}

interface RSIChartModalProps {
  isOpen: boolean;
  onClose: () => void;
  token: Token | null;
}

export default function RSIChartModal({ isOpen, onClose, token }: RSIChartModalProps) {
  const [rsiData, setRsiData] = useState<RSIData[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastPrice, setLastPrice] = useState<number | null>(null);
  // 根据代币类型设置不同的价格变化阈值
  const getPriceChangeThreshold = () => {
    // Meme币通常波动较大，设置较高阈值避免过于频繁的更新
    return 0.002; // 0.2% 价格变化阈值，适合Meme币
  };
  
  const [priceChangeThreshold] = useState(getPriceChangeThreshold());

  // 初始加载历史数据
  const loadInitialData = async () => {
    if (!token) return;
    
    setLoading(true);
    try {
      const response = await fetch(`/api/rsi-history?tokenId=${token.id}`);
      if (response.ok) {
        const data = await response.json();
        setRsiData(data);
        // 记录最后一条数据的价格
        if (data.length > 0) {
          setLastPrice(data[data.length - 1].price);
        }
      }
    } catch (error) {
      console.error('获取RSI数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 检查价格变化并更新RSI
  const checkPriceAndUpdateRSI = async () => {
    if (!token) return;
    
    try {
      // 获取当前价格
      const priceResponse = await fetch(`/api/current-price?contractAddress=${token.contractAddress}&chain=${token.chain}`);
      if (priceResponse.ok) {
        const priceData = await priceResponse.json();
        const currentPrice = priceData.price;
        
        // 检查价格变化是否达到阈值
        if (lastPrice !== null) {
          const priceChangePercent = Math.abs(currentPrice - lastPrice) / lastPrice;
          
          // 如果价格变化小于阈值，不更新RSI
          if (priceChangePercent < priceChangeThreshold) {
            console.log(`价格变化${(priceChangePercent * 100).toFixed(3)}%，未达到阈值${(priceChangeThreshold * 100).toFixed(1)}%，跳过RSI更新`);
            return;
          }
        }
        
        // 价格变化达到阈值，获取新的RSI数据点
        const response = await fetch(`/api/rsi-latest?tokenId=${token.id}`);
        if (response.ok) {
          const newData = await response.json();
          if (newData.length > 0) {
            const newPoint = newData[0];
            
            // 增量更新RSI数据，图表会自动重新渲染新增的数据点
            console.log(`RSI图表新增数据点: 时间=${new Date(newPoint.timestamp).toLocaleTimeString()}, RSI=${newPoint.rsi}, 价格=${currentPrice}`);
            
            setRsiData(prevData => {
              // 添加新的数据点到状态中
              const updated = [...prevData, newPoint];
              
              // 保持最多4小时的数据（约240个数据点）
              const maxPoints = 240;
              if (updated.length > maxPoints) {
                return updated.slice(-maxPoints);
              }
              return updated;
            });
            
            // 更新最后的价格
            setLastPrice(currentPrice);
            
            console.log(`RSI图表更新: 价格变化${((Math.abs(currentPrice - (lastPrice || 0)) / (lastPrice || 1)) * 100).toFixed(3)}%, 新RSI=${newPoint.rsi}, 价格=${currentPrice}`);
          }
        }
      }
    } catch (error) {
      console.error('检查价格变化失败:', error);
    }
  };

  useEffect(() => {
    if (isOpen && token) {
      // 初始加载历史数据
      loadInitialData();
      
      // 每2秒检查价格变化，只有达到阈值才更新RSI
      const interval = setInterval(checkPriceAndUpdateRSI, 2000);
      return () => clearInterval(interval);
    }
  }, [isOpen, token, lastPrice, priceChangeThreshold]);

  // ECharts配置 - 只显示RSI指标
  const getChartOption = () => {
    const times = rsiData.map(item => new Date(item.timestamp).toLocaleTimeString());
    const rsiValues = rsiData.map(item => item.rsi);

    return {
      title: {
        text: `${token?.symbol} RSI 指标`,
        left: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        },
        formatter: function(params: any) {
          const time = params[0].axisValue;
          const rsi = params[0].value;
          return `<div>
            <div>时间: ${time}</div>
            <div>RSI: ${rsi}</div>
          </div>`;
        }
      },
      legend: {
        data: ['RSI'],
        textStyle: {
          color: '#ffffff'
        },
        top: 30
      },
      grid: {
        left: '10%',
        right: '10%',
        top: '15%',
        bottom: '15%'
      },
      xAxis: {
        type: 'category',
        data: times,
        axisLabel: {
          color: '#ffffff',
          rotate: 45
        },
        axisLine: {
          lineStyle: {
            color: '#666'
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          color: '#ffffff'
        },
        splitLine: {
          lineStyle: {
            color: '#333'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#666'
          }
        }
      },
      series: [
        {
          name: 'RSI',
          type: 'line',
          data: rsiValues,
          smooth: true,
          lineStyle: {
            color: '#00d4ff',
            width: 3
          },
          itemStyle: {
            color: '#00d4ff'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(0, 212, 255, 0.3)' },
                { offset: 1, color: 'rgba(0, 212, 255, 0.05)' }
              ]
            }
          },
          markLine: {
            data: [
              { 
                yAxis: 70, 
                lineStyle: { color: '#ff4757', type: 'dashed', width: 2 }, 
                label: { 
                  formatter: '超买线 70',
                  color: '#ffffff',
                  backgroundColor: '#ff4757',
                  padding: [4, 8],
                  borderRadius: 4
                } 
              },
              { 
                yAxis: 30, 
                lineStyle: { color: '#2ed573', type: 'dashed', width: 2 }, 
                label: { 
                  formatter: '超卖线 30',
                  color: '#ffffff',
                  backgroundColor: '#2ed573',
                  padding: [4, 8],
                  borderRadius: 4
                } 
              },
              { 
                yAxis: 50, 
                lineStyle: { color: '#666', type: 'solid', width: 1 }, 
                label: { 
                  formatter: '中性线 50',
                  color: '#999',
                  backgroundColor: 'transparent'
                } 
              }
            ]
          }
        }
      ]
    };
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-gray-900 rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-4">
          <div>
            <h2 className="text-xl font-bold text-white">
              {token?.name} ({token?.symbol}) RSI 图表
            </h2>
            <p className="text-gray-400 text-sm">{token?.chain} 链</p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        <div className="mb-4">
          <div className="flex justify-between items-center">
            <p className="text-gray-400 text-sm">
              智能RSI图表（价格变化≥0.1%时更新，最多显示4小时历史）
            </p>
            <div className="text-xs text-gray-500">
              阈值: {(priceChangeThreshold * 100).toFixed(1)}%
            </div>
          </div>
        </div>

        <div className="bg-gray-800 rounded-lg p-4">
          {loading ? (
            <div className="flex items-center justify-center h-96">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              <span className="ml-2 text-white">加载中...</span>
            </div>
          ) : rsiData.length > 0 ? (
            <ReactECharts
              option={getChartOption()}
              style={{ height: '400px', width: '100%' }}
              theme="dark"
              notMerge={false}
              lazyUpdate={true}
            />
          ) : (
            <div className="flex items-center justify-center h-96 text-gray-400">
              暂无RSI数据
            </div>
          )}
        </div>

        <div className="mt-4 p-4 bg-gray-800 rounded-lg">
          <h3 className="text-white font-semibold mb-2">RSI 指标说明</h3>
          <div className="text-sm text-gray-300 space-y-1">
            <p>• RSI &gt; 70: 超买区域，可能出现回调</p>
            <p>• RSI &lt; 30: 超卖区域，可能出现反弹</p>
            <p>• RSI 50: 中性区域</p>
            <p>• 基于1分钟K线数据计算，价格变化达到阈值时更新</p>
            <p>• 智能更新机制：避免无意义的微小波动，专注重要价格变化</p>
          </div>
        </div>

        <div className="flex justify-end mt-4">
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-500 transition-colors"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  );
}
